package com.maimao.order.client.factory;

import cn.hutool.core.util.StrUtil;
import com.maimao.core.model.resp.Result;
import com.maimao.model.info.input.UseCouponInput;
import com.maimao.model.user.input.UpdateIntegralInput;
import com.maimao.order.client.CouponClient;
import com.maimao.order.client.UserClient;
import feign.hystrix.FallbackFactory;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author MaoLin Wang
 * @date 2020/11/30 10:03 下午
 */
@Component
@Slf4j
public class CouponFallBackFactory implements FallbackFactory<CouponClient> {

    @Override
    public CouponClient create(Throwable cause) {
        String errorMsg = cause.getMessage() == null ? "" : cause.getMessage();

        return new CouponClient() {
            @Override
            public Result<Void> useCoupon(UseCouponInput useCouponInput) {
                StringBuilder sb = new StringBuilder();
                sb.append("调用[CouponClient-useCoupon({})]出错 :{}\n");
                boolean globalTc = false;
                if (!StrUtil.isBlank(RootContext.getXID())) {
                    try {
                        GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                        sb.append("执行回滚，xid:{}");
                        globalTc = true;
                    } catch (TransactionException e) {
                        e.printStackTrace();
                        log.error("回滚失败,降级方法:[CouponClient-useCoupon()],xid:{}", RootContext.getXID());
                    }
                }
                if (globalTc) {
                    log.error(sb.toString(), useCouponInput, errorMsg, RootContext.getXID());
                } else {
                    log.error(sb.toString(),useCouponInput, errorMsg);
                }

                return Result.fail(errorMsg);
            }


        };
    }
}
